import { ref } from 'vue'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'

export const useObserver = (apiFn) => {
  const list = ref([])
  const target = ref(null)
  // 组件懒加载 target为目标元素，使用插件@vueuse
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        // 显示到目标元素之后请求数据
        apiFn().then(({ result }) => {
          list.value = result
        })
        // 当显示到目标元素之后，停止检测
        stop()
      }
    }
  )
  return { list, target }
}

// 封装倒计时器
export const useCountDown = (time = 5) => {
  const countTime = ref(0)
  const { pause, resume } = useIntervalFn(() => {
    // console.log('定时器工作中')
    countTime.value--
    if (countTime.value <= 0) {
      pause()
    }
  }, 1000, { immediate: false })
  // 开启定时器
  const start = () => {
    if (countTime.value === 0) { countTime.value = time }
    resume()
  }
  // 暂停定时器
  const endFn = () => {
    pause()
  }
  return { countTime, start, endFn }
}
